import traceback
from models.hotspot import Hotspot
from extensions import db
from services.platform_crawl_manager import (
    get_platform_latest_crawl_at,
    set_platform_latest_crawl_at,
)
from services.constants import PLATFORM_CONFIG
from services.utils import format_paginated_result, prepare_hotspot_data
from crawlers.kr36 import get_hot_articles_from_36kr

# services/kr36.py
from crawlers.kr36 import (
    get_new_flash_from_36kr,
    get_web_news_from_36kr,
    get_zonghe_articles_from_36kr,
    get_hot_articles_from_36kr,
    get_bookmark_articles_from_36kr
)

def fetch_kr36_hotspot_to_db(crawl_at) -> None:
    """抓取36氪数据并存入数据库"""
    try:
        # 定义section和对应的函数
        section_functions = {
            "快讯": get_new_flash_from_36kr,
            "最新资讯": get_web_news_from_36kr,
            "综合榜": get_zonghe_articles_from_36kr,
            "人气榜": get_hot_articles_from_36kr,
            "收藏榜": get_bookmark_articles_from_36kr
        }

        # 获取36氪各个板块数据
        for section, func in section_functions.items():
            articles = func()
            new_articles = prepare_hotspot_data(articles, "36氪", section, crawl_at)

            # 批量插入数据到数据库
            if new_articles:
                db.session.bulk_insert_mappings(Hotspot, new_articles)
                db.session.commit()

        # 更新平台最新抓取时间
        set_platform_latest_crawl_at("36氪", crawl_at)
        print("36氪数据抓取并存入数据库成功")

    except Exception as e:
        db.session.rollback()
        print("36氪数据抓取并存入数据库失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e
def get_kr36_hotspot_from_db(section: str) -> list:
    """从数据库获取36氪数据

    Parameters:
        section: 板块名称

    Returns:
        数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("36氪")

        # 从数据库获取数据
        kr36_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["36氪"]["id"],
            section=PLATFORM_CONFIG["36氪"]["sections"][section],
            crawl_at=latest_crawl_at,
        ).all()

        return kr36_hotspots

    except Exception as e:
        print(f"从数据库中获取36氪{section}数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e

def get_kr36_hotspot_from_db_page(section: str, page: int, page_size: int) -> dict:
    """从数据库获取36氪数据（分页）

    Parameters:
        section: 板块名称
        page: 页码
        page_size: 每页大小

    Returns:
        数据列表
        {
            "pages": 总页数,
            "page": 当前页码,
            "per_page": 每页大小,
            "items": 数据列表,
            "total": 总数据条数
        }
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("36氪")

        # 从数据库获取数据，并根据order排序
        kr36_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["36氪"]["id"],
            section=PLATFORM_CONFIG["36氪"]["sections"][section],
            crawl_at=latest_crawl_at,
        ).order_by(Hotspot.order).paginate(page=page, per_page=page_size)

        return format_paginated_result(kr36_hotspots)

    except Exception as e:
        print(f"从数据库中获取36氪{section}数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e